package cn.sccl.dirms.topo.discovery.util;

import cn.sccl.dirms.topo.snmp.mib.IfEntry;
import cn.sccl.dirms.topo.snmp.util.SNMPConfig;
import cn.sccl.dirms.topo.snmp.util.SNMPUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class TestPortPacakgeTask implements Runnable {
    private String ip;
    private Map<String,List<List<IfEntry>>> result;
    private SNMPConfig snmpConfig;
    private int loopTimes = 5;
    private int interval = 60000;


    public TestPortPacakgeTask(String ip,
                               Map<String, List<List<IfEntry>>> resultList) {
        this.ip = ip;
        this.result = resultList;
        this.snmpConfig = new SNMPConfig();
        snmpConfig.setReadCommunity("sccl");
    }

    @Override
    public void run() {
        try {
            if (this.ip == null) return;
            for(int i=0;i<loopTimes;i++){
                System.out.println(ip+"第"+(i+1)+"次读取端口信息");
                List<IfEntry> result= portPackageThread();
                if (result != null) {
                    System.out.println(ip+"第"+(i+1)+"次读取端口信息--读取完毕。");
                    synchronized (this.result) {
                        if (this.result.containsKey(this.ip)) {
                            this.result.get(ip).add(result);
                        }else{
                            List<List<IfEntry>> list = new ArrayList<List<IfEntry>>();
                            list.add(result);
                            this.result.put(ip, list);
                        }
                    }
                }else{
                    System.out.println(ip+"第"+(i+1)+"次读取端口信息--读取无数据。");
                }
                if(i<(loopTimes-1)){
                    Thread.sleep(interval);
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private List<IfEntry> portPackageThread() {
        List<IfEntry> list = new ArrayList<IfEntry>();
        try {
            SNMPUtils snmp = new SNMPUtils();
            snmp.start(ip, snmpConfig);
            if (snmp.isReadable()) {
                list = snmp.getTable(IfEntry.class);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }
}